<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="id" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="Tracking" prop="trackingNumber">
        <el-input
          v-model="queryParams.trackingNumber"
          placeholder="请输入Tracking"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="upc" prop="upc">
        <el-input
          v-model="queryParams.upc"
          placeholder="请输入upc"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="quantity" prop="quantity">
        <el-input
          v-model="queryParams.quantity"
          placeholder="请输入quantity"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="user_name" prop="userName" label-width="100px">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入user_name"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['purchase:classification:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['purchase:classification:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['purchase:classification:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['purchase:classification:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleBulkConfirm"
          v-hasPermi="['purchase:classification:bulkconfirm']"
        >批量确认</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="classificationList" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="warehouse_name" align="center" prop="warehouseName" />
      <el-table-column label="Tracking" align="center" prop="trackingNumber" sortable="custom" />
      <el-table-column label="upc" align="center" prop="upc" sortable="custom" />
      <el-table-column label="quantity" align="center" prop="quantity" sortable="custom" />
      <el-table-column label="user_name" align="center" prop="userName" />
      <el-table-column label="update_time" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['purchase:classification:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['purchase:classification:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改classification对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="warehouse_name" prop="warehouseName"  label-width="150px">
          <el-input v-model="form.warehouseName" placeholder="请输入warehouse_name"  />
        </el-form-item>
        <el-form-item label="batch_number" prop="batchNumber" label-width="140px">
          <el-input v-model="form.batchNumber" placeholder="请输入batch_number" />
        </el-form-item>
        <el-form-item label="Tracking" prop="trackingNumber" label-width="150px">
          <el-input v-model="form.trackingNumber" placeholder="请输入Tracking" />
        </el-form-item>
        <el-form-item label="upc" prop="upc">
          <el-input v-model="form.upc" placeholder="请输入upc" />
        </el-form-item>
        <el-form-item label="quantity" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入quantity" />
        </el-form-item>
        <el-form-item label="note" prop="note">
          <el-input v-model="form.note" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="exception" prop="exception">
          <el-input v-model="form.exception" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量确认弹窗 -->
    <el-dialog :title="'批量确认入库'" :visible.sync="bulkConfirmVisible" width="800px" append-to-body>
      <el-form :model="bulkConfirmForm" ref="bulkConfirmForm" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="UPC" prop="upc">
              <el-input
                v-model="bulkConfirmForm.upc"
                placeholder="请输入UPC"
                @keyup.enter.native="searchByUPC"
              />
              <el-button type="primary" @click="searchByUPC" style="margin-top: 10px;">搜索</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批次号" prop="batchNumber">
              <el-select
                v-model="bulkConfirmForm.batchNumber"
                placeholder="请选择批次号"
                style="width: 100%;"
                @change="handleBatchChange"
              >
                <el-option
                  v-for="item in batchNumbers"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-table :data="bulkConfirmItems" border style="width: 100%">
          <el-table-column label="UPC" width="200">
            <template slot-scope="scope">
              {{ scope.row.upc }}
            </template>
          </el-table-column>
          <el-table-column label="数量" width="120">
            <template slot-scope="scope">
              {{ scope.row.quantity }}
            </template>
          </el-table-column>
          <el-table-column label="产品" width="300">
            <template slot-scope="scope">
              <div v-if="availableProducts[scope.row.upc] && availableProducts[scope.row.upc].length > 0">
                <el-select
                  v-model="scope.row.selectedProductId"
                  placeholder="请选择产品"
                  @change="handleProductSelect(scope.row)"
                >
                  <el-option
                    v-for="product in availableProducts[scope.row.upc]"
                    :key="product.productId"
                    :label="product.name"
                    :value="product.productId"
                  ></el-option>
                </el-select>
              </div>
              <div v-else>
                <span>-</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="bulkConfirmVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmBulk">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listClassification, getClassification, delClassification, addClassification, updateClassification } from "@/api/purchase/classification"
import { listInventory } from "@/api/purchase/inventory"

export default {
  name: "Classification",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // classification表格数据
      classificationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        trackingNumber: null,
        upc: null,
        quantity: null,
        userName: null,
        orderByColumn: '',  // 排序列
        isAsc: 'asc'        // 排序方式
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        trackingNumber: [
          { required: true, message: "Tracking不能为空", trigger: "blur" }
        ],
        upc: [
          { required: true, message: "upc不能为空", trigger: "blur" }
        ],
        quantity: [
          { required: true, message: "quantity不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "user_id不能为空", trigger: "blur" }
        ],
        warehouseId: [
          { required: true, message: "warehouse_id不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "status不能为空", trigger: "change" }
        ],
        creationTime: [
          { required: true, message: "creation_time不能为空", trigger: "blur" }
        ],
      },
      // 批量确认相关
      bulkConfirmVisible: false,
      bulkConfirmForm: {
        upc: '',
        batchNumber: ''
      },
      bulkConfirmItems: [],
      availableProducts: {}, // 存储每个UPC对应的产品列表
      selectedProducts: {},   // 存储已选择的产品信息
      upcs: [],               // UPC下拉选项（保留但不使用）
      batchNumbers: [],       // 批次号下拉选项
      allClassificationData: [] // 用于存储所有分类数据
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询classification列表 */
    getList() {
      this.loading = true
      listClassification(this.queryParams).then(response => {
        this.classificationList = response.rows
        this.total = response.total
        this.loading = false
        this.updateDropdownOptions()
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        warehouseName: null,
        batchNumber: null,
        trackingNumber: null,
        upc: null,
        quantity: null,
        userId: null,
        userName: null,
        warehouseId: null,
        productName: null,
        status: null,
        note: null,
        exception: null,
        creationTime: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 设置 batchNumber 默认值为当前时间年月日时分
      this.form.batchNumber = this.getCurrentDateTime()
      this.open = true
      this.title = "添加classification"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getClassification(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改classification"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateClassification(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addClassification(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除classification编号为"' + ids + '"的数据项？').then(function() {
        return delClassification(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('purchase/classification/export', {
        ...this.queryParams
      }, `classification_${new Date().getTime()}.xlsx`)
    },
    /** 处理排序变化 */
    handleSortChange({ column, prop, order }) {
      // 如果是 trackingNumber、upc 或 quantity 列的排序
      if (prop === 'trackingNumber' || prop === 'upc' || prop === 'quantity') {
        // 设置排序条件
        this.queryParams.orderByColumn = prop;
        this.queryParams.isAsc = order === 'ascending' ? 'asc' : 'desc';
        // 重新获取数据
        this.getList();
      }
    },
    /** 获取当前日期时间字符串（年月日时分） */
    getCurrentDateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      return `${year}${month}${day}${hours}${minutes}`;
    },
    /** 批量确认按钮点击 */
    handleBulkConfirm() {
      // 初始化数据
      this.bulkConfirmItems = []
      this.bulkConfirmForm.upc = ''
      this.bulkConfirmForm.batchNumber = ''

      // 加载所有数据
      this.loadAllData()

      // 显示弹窗
      this.bulkConfirmVisible = true
    },
    /** 加载所有数据 */
    loadAllData() {
      // 重置查询参数
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 9999 // 设置一个很大的页码大小以获取所有数据

      // 获取所有数据
      listClassification(this.queryParams).then(response => {
        this.allClassificationData = response.rows

        // 将所有数据作为默认显示数据
        this.bulkConfirmItems = this.allClassificationData.map(item => ({
          upc: item.upc,
          quantity: item.quantity,
          selectedProductId: null
        }))

        // 更新批次号下拉选项
        this.updateBatchNumbers()

        // 加载可用产品
        this.loadAvailableProducts()
      })
    },
    /** 根据UPC搜索 */
    searchByUPC() {
      const upc = this.bulkConfirmForm.upc.trim()
      if (!upc) {
        this.$message.warning('请输入UPC')
        return
      }

      // 根据UPC筛选数据
      const filteredData = this.allClassificationData.filter(item => item.upc === upc)

      // 更新显示列表
      this.bulkConfirmItems = filteredData.map(item => ({
        upc: item.upc,
        quantity: item.quantity,
        selectedProductId: null
      }))

      // 清空批次号选择
      this.bulkConfirmForm.batchNumber = ''
    },
    /** 处理批次号变更 */
    handleBatchChange(batchNumber) {
      if (!batchNumber) {
        // 如果没有选择批次号，则显示所有数据
        this.bulkConfirmItems = this.allClassificationData.map(item => ({
          upc: item.upc,
          quantity: item.quantity,
          selectedProductId: null
        }))
        return
      }

      // 根据批次号筛选数据
      const filteredData = this.allClassificationData.filter(item => item.batchNumber === batchNumber)

      // 更新显示列表
      this.bulkConfirmItems = filteredData.map(item => ({
        upc: item.upc,
        quantity: item.quantity,
        selectedProductId: null
      }))

      // 清空UPC搜索
      this.bulkConfirmForm.upc = ''
    },
    /** 更新批次号下拉选项 */
    updateBatchNumbers() {
      // 获取所有批次号
      this.batchNumbers = [...new Set(this.allClassificationData.map(item => item.batchNumber))].sort()
    },
    /** 加载可用产品 */
    loadAvailableProducts() {
      // 获取所有库存产品
      listInventory({}).then(response => {
        const inventoryList = response.rows

        // 构建每个UPC对应的产品列表
        this.availableProducts = {}
        inventoryList.forEach(product => {
          if (!this.availableProducts[product.upc]) {
            this.availableProducts[product.upc] = []
          }
          this.availableProducts[product.upc].push({
            productId: product.productId,
            name: product.name
          })
        })
      })
    },
    /** 处理产品选择 */
    handleProductSelect(row) {
      // 当用户选择产品时，可以在这里处理逻辑
      console.log('选择了产品:', row.selectedProductId)
    },
    /** 确认批量操作 */
    confirmBulk() {
      // 验证是否有未选择产品的项目
      const unselectedItems = this.bulkConfirmItems.filter(item => !item.selectedProductId)
      if (unselectedItems.length > 0) {
        this.$message.warning('请为所有项目选择产品')
        return
      }

      // 这里可以添加实际的批量确认逻辑
      this.$message.success('批量确认成功')
      this.bulkConfirmVisible = false

      // 清空数据
      this.bulkConfirmItems = []
      this.bulkConfirmForm.upc = ''
      this.bulkConfirmForm.batchNumber = ''
    },
    /** 更新下拉选项 */
    updateDropdownOptions() {
      // 获取所有批次号
      this.batchNumbers = [...new Set(this.classificationList.map(item => item.batchNumber))].sort()

      // 获取所有UPC
      this.upcs = [...new Set(this.classificationList.map(item => item.upc))].sort()
    }
  }
}
</script>
